import { Injectable } from '@nestjs/common'
import { ArticleEntity } from 'src/entities/article.entity'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { createArticleDto } from './dto/create-article.dto'
import to from 'await-to-js'
import { UserEntity } from 'src/entities/user.entity'
@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(ArticleEntity)
    private readonly articleRepository: Repository<ArticleEntity>,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}
  async create(
    body: createArticleDto,
    user: UserEntity,
  ): Promise<[Error, ArticleEntity]> {
    const userEntity = await this.userRepository.findOne(user.id)
    const article = await this.articleRepository.create(body)
    article.user = userEntity
    const [err] = await to(this.articleRepository.insert(article))
    return [err, article]
  }
}
